<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
require_once('config.php');
require_once(DIR_SYSTEM . 'library/db.php');


define('FIX_CODING', 'UTF-8');

setlocale(LC_CTYPE, 'ru_RU.utf8');
/**
 * Функция получения заказов
 */
function upload_orders_simplexml(&$db) {
    $query = $db->query("SELECT * FROM  `" . DB_PREFIX . "order` ");
    $no_spaces = '<?xml version="1.0" encoding="UTF-8"?><КоммерческаяИнформация ВерсияСхемы="2.04"  ДатаФормирования="' . date ('Y-m-d') . 'T' . date ('H:m:s') . '"></КоммерческаяИнформация>';
    $xml = new SimpleXMLElement($no_spaces);
    foreach ($query->rows as $order) {
        $doc = $xml->addChild("Документ");
        $doc->addChild("Ид", $order['uuid']);
        $doc->addChild("Номер", $order['order_id']);
        $doc->addChild("Дата",  date ('Y-m-d'));
        $doc->addChild("ХозОперация", 'Заказ товара');
        $doc->addChild("Роль", 'Продавец');
        $val = $order['currency'];
        switch ($val) {
                case 'руб' :
                        $val = 'RUB';
                        break;
                case 'RUB' :
                        $val = 'руб';
                        break;
        }
        $doc->addChild("Валюта", $val);
        $doc->addChild("Курс", $order['value']);
        $doc->addChild("Сумма", $order['total']);

        $customers_xml = $doc->addChild("Контрагенты");


        $customer_query = $db->query("SELECT * FROM `" . DB_PREFIX . "customer` WHERE `customer_id` = '" . $order['customer_id'] . "'");
        foreach ($customer_query->rows as $customer) {
            $customer_xml = $customers_xml->addChild("Контрагент");
            $customer_xml->addChild('Ид', $customer['uuid']);
            $customer_xml->addChild('Наименование', $order['shipping_company']);
            $customer_xml->addChild('Роль', 'Покупатель');
            $reqs_xml = $customer_xml->addChild('РеквизитыЮрЛица');
            $reqs_xml->addChild('ОфициальноеНаименование', $order['shipping_company']);
            $reqs_xml->addChild('ИНН', $customer['req_inn']);
            $reqs_xml->addChild('КПП', $customer['req_kpp']);
        }

        //Товары
        $products_xml = $doc->addChild("Товары");
        $product_query = $db->query("SELECT `" . DB_PREFIX . "order_product`.*, `" . DB_PREFIX . "product`.`uuid` FROM  `" . DB_PREFIX . "order_product` LEFT JOIN  `" . DB_PREFIX . "product` ON  `" . DB_PREFIX . "order_product`.`product_id` =  `" . DB_PREFIX . "product`.`product_id` WHERE `" . DB_PREFIX . "order_product`.`order_id` = '" . $order['order_id'] . "'");
        foreach ($product_query->rows as $order_product) {
            $product_xml = $products_xml->addChild('Товар');
            $product_xml->addChild('Ид', $order_product['uuid']);
            $product_xml->addChild('ЦенаЗаЕдиницу', $order_product['price']);
            $product_xml->addChild('Количество', $order_product['quantity']);
            $product_xml->addChild('Сумма', $order_product['total']);
        }
    }
    if (FIX_CODING == 'UTF-8') {
        header("Content-type: text/xml; charset=windows-1251");
        print iconv("utf-8", "cp1251", $xml->asXML());
    } else if (FIX_CODING == 'UTF-16') {
        header("Content-type: text/xml; charset=windows-1251");
        print iconv("UTF-16", "CP1251", $xml->asXML());
    } else {
        print $xml->asXML();
    }
}

function upload_orders(&$db) {
    $query = $db->query("SELECT * FROM  `" . DB_PREFIX . "order` ");

    $memory = xmlwriter_open_memory();
    xmlwriter_start_document($memory, '1.0', 'UTF-8');
    xmlwriter_start_element($memory, 'КоммерческаяИнформация');
    foreach ($query->rows as $order) {
        xmlwriter_start_element($memory, 'Документ');
        //Реквизиты заказа
        xmlwriter_start_element($memory, 'Ид');
        xmlwriter_text($memory, $order['uuid']);
        xmlwriter_end_element($memory);

        xmlwriter_start_element($memory, 'ХозОперация');
        xmlwriter_text($memory, 'Заказ товара');
        xmlwriter_end_element($memory);

        xmlwriter_start_element($memory, 'Роль');
        xmlwriter_text($memory, 'Продавец');
        xmlwriter_end_element($memory);

        xmlwriter_start_element($memory, 'Валюта');
        xmlwriter_text($memory, $order['currency']);
        xmlwriter_end_element($memory);
        xmlwriter_start_element($memory, 'Курс');
        xmlwriter_text($memory, $order['value']);
        xmlwriter_end_element($memory);

        xmlwriter_start_element($memory, 'Сумма');
        xmlwriter_text($memory, $order['total']);
        xmlwriter_end_element($memory);

        xmlwriter_start_element($memory, "Контрагенты");
        $customer_query = $db->query("SELECT * FROM `" . DB_PREFIX . "customer` WHERE `customer_id` = '" . $order['customer_id'] . "'");
        foreach ($customer_query->rows as $customer) {
            xmlwriter_start_element($memory, "Контрагент");

            xmlwriter_start_element($memory, 'Ид');
            xmlwriter_text($memory, $customer['uuid']);
            xmlwriter_end_element($memory);
            xmlwriter_start_element($memory, 'Наименование');
            xmlwriter_text($memory, $order['shipping_company']);
            xmlwriter_end_element($memory);
            xmlwriter_start_element($memory, 'Роль');
            xmlwriter_text($memory, 'Покупатель');
            xmlwriter_end_element($memory);
            xmlwriter_start_element($memory, 'РеквизитыЮрЛица');
            xmlwriter_start_element($memory, 'ОфициальноеНаименование');
            xmlwriter_text($memory, $order['shipping_company']);
            xmlwriter_end_element($memory);
            xmlwriter_start_element($memory, 'ИНН');
            xmlwriter_text($memory, $customer['req_inn']);
            xmlwriter_end_element($memory);
            xmlwriter_start_element($memory, 'КПП');
            xmlwriter_text($memory, $customer['req_kpp']);
            xmlwriter_end_element($memory);
            xmlwriter_end_element($memory);

            xmlwriter_end_element($memory);
        }
        xmlwriter_end_element($memory);

        //Товары
        xmlwriter_start_element($memory, "Товары");
        $product_query = $db->query("SELECT * FROM  `" . DB_PREFIX . "order_product` LEFT JOIN  `" . DB_PREFIX . "product` ON  `" . DB_PREFIX . "order_product`.`product_id` =  `" . DB_PREFIX . "product`.`product_id` WHERE `" . DB_PREFIX . "order_product`.`order_id` = '" . $order['order_id'] . "'");
        foreach ($product_query->rows as $order_product) {
            xmlwriter_start_element($memory, 'Товар');
            xmlwriter_start_element($memory, 'Ид');
            xmlwriter_text($memory, $order_product['uuid']);
            xmlwriter_end_element($memory);

            xmlwriter_start_element($memory, 'ЦенаЗаЕдиницу');
            xmlwriter_text($memory, $order_product['price']);
            xmlwriter_end_element($memory);

            xmlwriter_start_element($memory, 'Количество');
            xmlwriter_text($memory, $order_product['quantity']);
            xmlwriter_end_element($memory);

            xmlwriter_start_element($memory, 'Сумма');
            xmlwriter_text($memory, $order_product['total']);
            xmlwriter_end_element($memory);

            xmlwriter_end_element($memory);
        }
        xmlwriter_end_element($memory);

        xmlwriter_end_element($memory);
    }
    xmlwriter_end_element($memory);

    $xml = xmlwriter_output_memory($memory, true);
//
//    $memory = xmlwriter_open_memory();
//    xmlwriter_start_document($memory,'1.0','UTF-8');
//
//    foreach ($query as $key => $value){
//        xmlwriter_start_element ($memory,'Документ');
//            xmlwriter_start_element ($memory,'Ид');
//            xmlwriter_text($memory, $value['uuid']);
//            xmlwriter_end_element($memory);
//
//            xmlwriter_start_element ($memory,'ХозОперация');
//            xmlwriter_text($memory, 'Заказ товара');
//            xmlwriter_end_element($memory);
//
//            xmlwriter_start_element ($memory,'Роль');
//            xmlwriter_text($memory, 'Продавец');
//            xmlwriter_end_element($memory);
//
//            xmlwriter_start_element ($memory,'Валюта');
//            xmlwriter_text($memory, $value['currency']);
//            xmlwriter_end_element($memory);
//            xmlwriter_start_element ($memory,'Курс');
//            xmlwriter_text($memory, $value['value']);
//            xmlwriter_end_element($memory);
//
//            xmlwriter_start_element ($memory,'Сумма');
//            xmlwriter_text($memory, $value['total']);
//            xmlwriter_end_element($memory);
//		//<СрокПлатежа>2010-08-04</СрокПлатежа>
//        xmlwriter_end_element($memory);
//    }
//    xmlwriter_end_element($memory);
//
//    $xml = xmlwriter_output_memory($memory,true);
    echo $xml;
}

/**
 * Функция возвращает xml документ с заказами
 */
function export_to_cml2() {
    $db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
    upload_orders_simplexml($db);
}

?>
